package com.acme.bankapp.service.bank;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.acme.bankapp.domain.account.AbstractAccount;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.client.Client;
import com.acme.bankapp.service.exception.FileFormatException;

public class BankReport {
	
	public BankReport(){
		
	}
	
	public void addClient(Bank bank, String str) {
		BankDataLoaderService bankDataLoader = new BankDataLoaderService();
		try {
			Client client = bankDataLoader.readNextClient(str);
			BankApplication.addClient(bank, client);
		} catch (FileFormatException e) {
			System.out.println(e.getMessage());
		}
	}

	public String getBalance(Bank bank) {
		return BankService.getBalance(bank);

	}
	
	public int getNbOfClients(Bank bank) {
        return bank.getCountClients();
}

	public int getNbOfAccounts(Bank bank) {
        int nAccounts = 0;
        for (Client client : bank.getClients()) {
                nAccounts += client.getAccounts().size();
        }
        
        return nAccounts;
}

	public List<AbstractAccount> getAccountsSortedBySum(Bank bank) {
		List<AbstractAccount> accs = new ArrayList<>();
		for (Client client : bank.getClients()) {
			for (AbstractAccount abstractAccount : client.getAccounts()) {
				accs.add(abstractAccount);
			}
		}

		Collections.sort(accs, new Comparator<AbstractAccount>() {

			@Override
			public int compare(AbstractAccount o1, AbstractAccount o2) {
				double amount1 = o1.maximumAmountToWithdraw();
				double amount2 = o2.maximumAmountToWithdraw();

				if (amount1 < amount2)
					return 1;
				else if (amount1 > amount2)
					return -1;
				else
					return 0;
			}

		});

		return accs;
	}

	public double getBankCredit(Bank bank) {
		double sum = 0;
		for (Client client : bank.getClients()) {
			for (AbstractAccount account : client.getAccounts()) {
				if (account.getBalance() < 0) {
					sum -= account.getBalance();
				}
			}
		}
		return sum;
	}

	public Map<Client, ArrayList<AbstractAccount>> getClientsAccountsMap(Bank bank) {
		
		Map<Client, ArrayList<AbstractAccount>> map = new HashMap<Client, ArrayList<AbstractAccount>>();

		for (Client client : bank.getClients()) {
			ArrayList<AbstractAccount> accounts = new ArrayList<>();
			for (AbstractAccount account : client.getAccounts()) {
				accounts.add(account);
			}
			map.put(client, accounts);
		}

		return map;
	}

}
